<?php

namespace System\library\logger\writers;

use System\library\Logger;
use System\library\Debugger;

/**
 * <b>Class</b> :        Display<br>
 * <b>Fonction</b> :     Writer "Display" pour le logger, permet d'afficher les logs
 * <br>
 * @version              1.0
 * @author               Dread <dreadlokeur@gmail.com>
 * @license              Licence publique générale GNU http://www.gnu.org/licenses/gpl.html
 * @copyright            Copyright 2011 - MidichloriansPHP and contributors
 * @package              System
 * @subpackage           library\logger\writers
 *
 * @see \SplObserver
 */
class Display implements \SplObserver {

    public function update(\SplSubject $subject, $lastLogOnly = false, $bottomLogs = false) {
        $logs = ($bottomLogs) ? $bottomLogs : $subject->getLogs();
        $groups = $subject->getGroups();
        // Recuperation du dernier log
        if ($lastLogOnly) {
            $lastLog = array();
            $lastLog[] = end($logs);
            $logs = $lastLog;
        }
        $bottomLogs = array();
        // Traitement des logs
        foreach ($logs as &$log) {
            if (is_array($log)) {
                if ($groups[$log[0]->group]->onBottom) {
                    $groups[$log[0]->group]->onBottom = false;
                    $bottomLogs[] = $log;
                } else {
                    $this->_displayGroupTop($log[0]->date, $groups[$log[0]->group]->label);
                    foreach ($log as &$l)
                        $this->_displayLog($l->message, $l->level, $l->date);
                    $this->_displayGroupBottom($l->date);
                }
            } else
                $this->_displayLog($log->message, $log->level, $log->date);
        }
        if (count($bottomLogs) > 0)
            $this->update($subject, false, $bottomLogs);
    }

    private function _displayLog($message, $level, $date) {
        $head = '[' . $date . '][' . Logger::getLevelName($level) . ']]';
        echo $head . $message . chr(10) . '<br/>';
    }

    private function _displayGroupTop($date, $label) {
        echo '[' . $date . '][GROUP]' . str_pad($label, 100, '-', STR_PAD_BOTH) . chr(10) . '<br/>';
    }

    private function _displayGroupBottom($date) {
        echo '[' . $date . '][GROUP]' . str_repeat('-', 102) . chr(10) . '<br/>';
    }

}

?>
